package by.yakusekmaxim.bookgid.webapp.page.admin.series;

import javax.inject.Inject;

import org.apache.wicket.bean.validation.PropertyValidator;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.SubmitLink;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.ResourceModel;

import by.yakusekmaxim.bookgid.datamodel.Series;
import by.yakusekmaxim.bookgid.services.SeriesService;
import by.yakusekmaxim.bookgid.webapp.page.AdminLayout;

public class EditSeriesPage extends AdminLayout {

	@Inject
	private SeriesService seriesService;
	
	public EditSeriesPage(final Series series){
		if (series.getId() == null) {
			add(new Label("pageNameLabel", new ResourceModel("p.admin.editgenre.pageName.newSeries").getObject()));
		}else {
			add(new Label("pageNameLabel", new ResourceModel("p.admin.editgenre.pageName").getObject() + series.getName()));
		}
		
		
		Form<Series> form = new Form<Series>("form",
				new CompoundPropertyModel<Series>(series));
		final Label tfId = new Label("id", series.getId());
		form.add(tfId);

		final TextField<String> tfName = new TextField<String>("name");
		tfName.add(new PropertyValidator<String>());
		form.add(tfName);
		
		
		form.add(new SubmitLink("cancel") {
			@Override
			public void onSubmit() {
				super.onSubmit();

				SeriesPage page = new SeriesPage();
				setResponsePage(page);
			}

			@Override
			public void onError() {

				super.onError();
			}
		});

		form.add(new SubmitLink("save") {
			@Override
			public void onSubmit() {
				super.onSubmit();

				seriesService.saveOrUpdate(series);

				SeriesPage page = new SeriesPage();

//				page.error("Custom error");
				page.info("Профиль ID: " + series.getId() + " сохранён!");
//				page.warn("Custom warn");

				setResponsePage(page);
			}

			@Override
			public void onError() {

				super.onError();
			}
		});
		
		add(form);
		
	}
	
	@Override
	protected IModel<String> getPageTitle() {
		return new ResourceModel("p.admin.editauthor.pageTitle");
	}

	@Override
	protected WebMarkupContainer getTarget() {
		return targetSeries;
	}
}
